/*
 * Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved.
 */
package com.stm.main;

import java.io.IOException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.animation.FadeTransition;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.collections.ListChangeListener.Change;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.event.EventType;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.TableColumn.CellDataFeatures;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.Region;
import javafx.stage.Stage;
import javafx.util.Callback;
import javafx.util.Duration;

public class STMMainController implements Initializable {

    @FXML
    MenuBar menuBar;
    @FXML
    TreeView<String> treeView;
    @FXML
    TextField synopsis;
    @FXML
    Label displayedIssueLabel;  // the displayedIssueLabel will contain a concatenation of the 
    //   the project name and the bug id.
    @FXML
    AnchorPane details;
    @FXML
    SplitPane splitPane;
    @FXML
    AnchorPane mainPane;
    @FXML
    Region titleLine;
    @FXML
    TextArea descriptionValue;
    @FXML
    TextField activityField;
    @FXML
    TextField statusValue;
    @FXML
    TextField priorityValue;
    @FXML
    Label creationTimeValue;
    @FXML
    Label messageBar;
    @FXML
    TabPane tabPane;
    @FXML
            
    BorderPane borderPane;
    ResourceBundle bundle;

    boolean session = false;
    
    /**
     * Initializes the controller class.
     */
    @Override
    public void initialize(URL url, ResourceBundle rsrcs) {
        assert descriptionValue != null : "fx:id=\"descriptionValue\" was not injected: check your FXML file 'IssueTrackingLite.fxml'.";
        assert details != null : "fx:id=\"details\" was not injected: check your FXML file 'IssueTrackingLite.fxml'.";
        assert displayedIssueLabel != null : "fx:id=\"displayedIssueLabel\" was not injected: check your FXML file 'IssueTrackingLite.fxml'.";
        assert messageBar != null : "fx:id=\"messageBar\" was not injected: check your FXML file 'IssueTrackingLite.fxml'.";
        assert treeView != null : "fx:id=\"treeView\" was not injected: check your FXML file 'IssueTrackingLite.fxml'.";

        // When running IssueTracking sample both statusValue and priorityValue
        // are initialized because they're defined in the FXML file.
        // It's only when we build then run the IssueTrackingStepByStep sample
        // that we need to initialize them here because the FXML doesn't contain
        // them (the StepByStep flavor is less rich, to keep the number of steps
        // low).
        if (statusValue == null) {
            statusValue = new TextField();
        }
        if (priorityValue == null) {
            priorityValue = new TextField();
        }
        System.out.println(this.getClass().getSimpleName() + ".initialize");
        bundle = ResourceBundle.getBundle("com.stm.main.bundle_ko_KR");
        setTreeMenu();
        tabPane.setUserData(this);
    }
    
    /**
     * 메뉴아이템 클릭시 해당 팬 표시
     *
     * @param event
     */
    public void menuOnAction(ActionEvent event) {
        MenuItem item = (MenuItem) event.getSource();
        String tabTitle = item.getText();

        setTab(tabTitle);

    }

    public void checkSession(){
        if(session){
            
        }else{
            logout(null);
        }
    }
    /**
     * 팬 닫기
     *
     * @param event
     */
    public void btnPaneCloseOnAction(ActionEvent event) {
        Button btn = (Button) event.getSource();
        TitledPane tp = (TitledPane) btn.getParent().getParent().getParent().getParent().getParent();
        tp.setVisible(false);
    }
    FadeTransition messageTransition = null;

    public void displayMessage(String message) {
        if (messageBar != null) {
            if (messageTransition != null) {
                messageTransition.stop();
            } else {
                messageTransition = new FadeTransition(Duration.millis(2000), messageBar);
                messageTransition.setFromValue(1.0);
                messageTransition.setToValue(0.0);
                messageTransition.setDelay(Duration.millis(1000));
                messageTransition.setOnFinished(new EventHandler<ActionEvent>() {

                    @Override
                    public void handle(ActionEvent event) {
                        messageBar.setVisible(false);
                    }
                });
            }
            messageBar.setText(message);
            messageBar.setVisible(true);
            messageBar.setOpacity(1.0);
            messageTransition.playFromStart();
        }
    }

    private void setPaneOnTop(ActionEvent event) {
        MenuItem item = (MenuItem) event.getSource();
        String selectedItem = item.getText();

        if (item != null) {
            ObservableList<Node> list = mainPane.getChildren();
            Iterator<Node> iter = list.iterator();
            while (iter.hasNext()) {
                Node o = iter.next();
                if (o instanceof TitledPane) {
                    TitledPane tp = (TitledPane) o;
                    String title = tp.getText();
                    if (selectedItem.equals(title)) {
                        System.out.println(tp.getText());
                        o.setVisible(true);
                        tp.setExpanded(true);

                    } else {
                        //o.setVisible(false);
                        //tp.setExpanded(false);
                    }
                }
            }
        }
    }

    private void setTreeMenu() {
        TreeItem<String> root = new TreeItem<String>("treeMenu");

        ArrayList<TreeItem<String>> m1 = new ArrayList<TreeItem<String>>();
        ArrayList<TreeItem<String>> m2 = new ArrayList<TreeItem<String>>();
        ArrayList<TreeItem<String>> m3 = new ArrayList<TreeItem<String>>();
        TreeItem<String> menu1 = new TreeItem<String>(bundle.getString("menu1"));
        TreeItem<String> menu2 = new TreeItem<String>(bundle.getString("menu2"));
        TreeItem<String> menu3 = new TreeItem<String>(bundle.getString("menu3"));
        m1.add(new TreeItem<String>(bundle.getString("menu1.01")));
        m1.add(new TreeItem<String>(bundle.getString("menu1.02")));
        m2.add(new TreeItem<String>(bundle.getString("menu2.01")));
        m2.add(new TreeItem<String>(bundle.getString("menu2.02")));
        m2.add(new TreeItem<String>(bundle.getString("menu2.03")));
        m2.add(new TreeItem<String>(bundle.getString("menu2.04")));
        m2.add(new TreeItem<String>(bundle.getString("menu2.05")));
        m2.add(new TreeItem<String>(bundle.getString("menu2.06")));
        m3.add(new TreeItem<String>(bundle.getString("menu3.01")));

        menu1.getChildren().addAll(m1);
        menu2.getChildren().addAll(m2);
        menu3.getChildren().addAll(m3);
        root.getChildren().addAll(menu1, menu2, menu3);

        root.setExpanded(true);
        menu1.setExpanded(true);
        menu2.setExpanded(true);
        menu3.setExpanded(true);

        treeView.setShowRoot(false);
        treeView.setRoot(root);
        treeView.getSelectionModel().setSelectionMode(SelectionMode.SINGLE);

        treeView.getSelectionModel().selectedItemProperty().addListener(treeMenuSelected);
    }
    /**
     * 트리메뉴선택시 탭화면생성
     */
    private final ChangeListener<TreeItem<String>> treeMenuSelected = new ChangeListener<TreeItem<String>>() {

        @Override
        public void changed(ObservableValue<? extends TreeItem<String>> observable, TreeItem<String> oldValue, TreeItem<String> newValue) {
            //projectUnselected(oldValue);
            String tabTitle = newValue.getValue();
            System.out.println(tabTitle);
            setTab(tabTitle);
        }
    };

    private boolean isVoid(Object o) {
        if (o instanceof String) {
            return isEmpty((String) o);
        } else {
            return o == null;
        }
    }

    private boolean isEmpty(String s) {
        return s == null || s.trim().isEmpty();
    }

    private boolean equal(Object o1, Object o2) {
        if (isVoid(o1)) {
            return isVoid(o2);
        }
        return o1.equals(o2);
    }

    /**
     * 탭 생성
     *
     * @param tabTitle
     */
    private void setTab(String tabTitle) {
        try {
            //setPaneOnTop(event);

            AnchorPane pane = (AnchorPane) FXMLLoader.load(getClass().getResource("SearchHolder.fxml"));
            Tab tab = new Tab();
            tab.setText(tabTitle);
            tab.setContent(pane);

            borderPane.setVisible(false);
            tabPane.setVisible(true);
            tabPane.getTabs().add(tab);
            SingleSelectionModel<Tab> selectionModel = tabPane.getSelectionModel();
            selectionModel.select(tab); //select by object

            tab.setOnClosed(new EventHandler<Event>() {

                @Override
                public void handle(Event event) {
                    showMainImage();
                }
            });
        } catch (IOException ex) {
            Logger.getLogger(STMMainController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void showMainImage() {
        if (0 == tabPane.getTabs().size()) {
            tabPane.setVisible(false);
            borderPane.setVisible(true);
        }
    }

    public void login() {
        closeAllOnAction(null);
        menuBar.setDisable(false);
        treeView.setDisable(false);
        
        session = true;
    }

    private static enum SaveState {

        INVALID, UNSAVED, UNCHANGED
    }

    private String formatDate(long date) {
        final SimpleDateFormat format = new SimpleDateFormat();
        return format.format(new Date(date));
    }

    /**
     * 탭팬 컨텍스트 메뉴 close all tabs 이벤트핸들러
     *
     * @param event
     */
    public void closeAllOnAction(ActionEvent event) {
        tabPane.getTabs().size();
        for (int i = tabPane.getTabs().size() - 1; i >= 0; i--) {
            tabPane.getTabs().remove(i);
        }

        //UI그린후에 메인이미지표시
        Timer timer = new Timer();
        timer.schedule(new UIWaiter(), 1000);

    }

    /**
     * 메인이미지표시 타이머태스크
     */
    public class UIWaiter extends TimerTask {

        @Override
        public void run() {
            showMainImage();
        }
    }

    public void logout(ActionEvent event) {
        closeAllOnAction(null);
        menuBar.setDisable(true);
        treeView.setDisable(true);

        try {
            AnchorPane pane = (AnchorPane) FXMLLoader.load(getClass().getResource("LogIn.fxml"));
            Tab tab = new Tab();
            tab.setText(bundle.getString("login"));
            tab.setContent(pane);

            borderPane.setVisible(false);
            tabPane.setVisible(true);
            tabPane.getTabs().add(tab);
            SingleSelectionModel<Tab> selectionModel = tabPane.getSelectionModel();
            selectionModel.select(tab); //select by object

            tab.setOnClosed(new EventHandler<Event>() {

                @Override
                public void handle(Event event) {
                    showMainImage();
                }
            });
        } catch (IOException ex) {
            Logger.getLogger(STMMainController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void logInOnMouseClicked(MouseEvent event) {
        showMainImage();
        menuBar.setDisable(false);
        treeView.setDisable(false);
    }
}
